<template>
	<view class="pages">
		<!-- #ifdef APP -->
		<ykAuthpup ref="authpup" type="top" @changeAuth="changeAuth" permissionID="WRITE_EXTERNAL_STORAGE"></ykAuthpup>
		<!-- #endif -->
		<view class="log">
			<image src="https://img.aibbyp.com/wechat/newImg/login.png" mode=""></image>
		</view>
		<view class="login">
			<view class="cu-bar bg-white " style="justify-content: center;">
				<view class="center-title">
					<view class="action border-title" @tap="swItch = true">
						<text class="left-title" :style="swItch?'color: #FF4530;left:unset':''">短信登录</text>
						<text class="bg-grey"
							:style="swItch?'background-color: #FF4530;left: revert;':'background-color:#FFF'"></text>
					</view>
					<view class="action border-title" @tap="swItch = false">
						<text class="left-title" :style="!swItch?'color: #FF4530;left:unset':''">密码登录</text>
						<text class="bg-grey"
							:style="!swItch?'background-color: #FF4530;left: revert;':'background-color:#FFF'"></text>
					</view>
				</view>
			</view>
			<view class="input-box">
				<view class="cu-form-group margin-top border-botttom">
					<input placeholder="请输入手机号" name="input" type="number" maxlength="11" @input="change"
						v-model="FormData.phone"></input>
				</view>
				<view class="cu-form-group border-botttom">
					<input v-if="swItch" :placeholder="swItch?'请输入短信验证码':'请输入短信验证码'" name="input" @input="change"
						type="number" v-model="FormData.sendCode" maxlength="6"></input>
					<input v-if="!swItch" :placeholder="swItch?'请输入登录密码':'请输入登录密码'" name="input" @input="change"
						:password="!swItch?true:false" v-model="FormData.sendPass"></input>
					<button class='cu-btn bg-green' @tap="xiaokeaiShowtrue" v-show="swItch">{{sendText}}</button>
				</view>
			</view>
			<view class="bottom-title">
				<u-checkbox-group :class="checked ? 'shake-horizontal' : ''" class="auth-clause">
					<u-checkbox active-color="red" class="orange" :class="checked ? 'checked' : ''" v-model="checked" />
				</u-checkbox-group>
				<agreement></agreement>
			</view>
		</view>
		<!-- #ifdef MP-WEIXIN -->
		<view class="f24 tac pg24">
			<button class="btngongjiang" open-type="getPhoneNumber"
				@getphonenumber="decryptPhoneNumber($event,'gongjiang')">工匠接单？ <text class="error">去入驻</text></button>
			<!-- <button class="btngongjiang" @click="loginWX" v-if="!checked">工匠接单？ <text class="error">去入驻</text></button> -->

		</view>
		<!-- #endif -->

		<view class="btn">
			<button class="cu-btn block bg-blue margin-tb-sm lg loginBtn" :disabled="disabled"
				@tap="login">{{swItch?'手机号登录':'密码登录'}}</button>
		</view>
		<!-- #ifdef MP-WEIXIN -->
		<view class="btn">
			<button class="cu-btn block wechatBtn margin-tb-sm lg loginBtn " open-type="getPhoneNumber"
				@getphonenumber="decryptPhoneNumber">一键登录</button>
			<!-- <button class="cu-btn block wechatBtn margin-tb-sm lg loginBtn " @click="loginWX"
				v-if="!checked">一键登录</button> -->
		</view>
		<!-- #endif -->
		<view class="password">
			<view>
				<!-- <text class="color" @tap="register">免费注册</text> -->
				<!-- <text class="xia">|</text> -->
				<text class="color" @tap="password">忘记密码</text>
			</view>
		</view>
		<view class="info f28 tac mt32" @click="goHome">
			返回主页
		</view>

		<!-- #ifdef APP -->
		<uni-id-pages-fab-login @checked='checked' ref="uniFabLogin"></uni-id-pages-fab-login>
		<!-- #endif -->
		<!-- #ifdef MP-WEIXIN -->
		<!-- //第三方登录 -->
		<!-- <uni-id-pages-fab-login ref="uniFabLogin"></uni-id-pages-fab-login> -->
		<!-- #endif -->

		<!-- <view class="bottom-xian">
			<image src="https://img.aibbyp.com/wechat/newImg/lsers.png" mode=""></image>
		</view>
		<view class="whactLog">	
			<view class="imgSrc">
				<view>
					<image src="https://img.aibbyp.com/wechat/newImg/wechat.png" mode=""></image>
				</view>
				<view>微信登录</view>
			</view>
			<view class="imgSrc">
				<view>
					<image src="https://img.aibbyp.com/wechat/newImg/zhifubao.png" mode=""></image>
				</view>
				<view>支付宝登录</view>
			</view>
			<view class="imgSrc">
				<view>
					<image src="https://img.aibbyp.com/wechat/newImg/web.png" mode=""></image>
				</view>
				<view>微博登录</view>
			</view>
		</view> -->
		<xiaokeai-humanCheck @success="onSuccess" @fail="onFail" :show="xiaokeaiShow" @close='xiaokeaiShow = false'
			@checkResult='checkResult' title="人机校验" closeBtnText="关闭" actionTips="请完成人机校验"
			checkSuccessText="校验成功"></xiaokeai-humanCheck>

	</view>
</template>
<script>
	// #ifdef APP
	import ykAuthpup from "@/components/yk-authpup/yk-authpup";
	// #endif
	export default {
		components: {
			// #ifdef APP
			ykAuthpup
			// #endif
		},
		data() {
			return {
				xiaokeaiShow: false,
				logoData: {},
				loginRes: {},
				FormData: {
					phone: '',
					send: '',
					sendCode: '',
					sendPass: '',
				},
				checked: false,
				sendText: '发送验证码',
				Code: '',
				swItch: true,
				disabled: true,
				getPhoneNumberData: {},
				getPhoneNumbertype: null,
				invitation_code: ''
			}
		},

		computed: {

		},
		onLoad() {
			console.log('---invitation_code--', uni.getStorageSync('invitation_code'));
		},
		onReady() {
			// #ifdef H5
			this.invitation_code = uni.getStorageSync('invitation_code')
			// #endif
			// #ifdef MP-WEIXIN
			this.invitation_code = uni.getStorageSync('invitation_code')
			// #endif
			//#ifdef APP-PLUS
			uni.preLogin({
				provider: 'univerify',
				success: () => {
					this.$refs.uniFabLogin.login_before('univerify')
				},
				fail: (err) => {}
			})
			//#endif
		},

		onShow() {
			// #ifdef MP-WEIXIN
			// 防止刷新登录态，uni.login code提前获取

			this.getCode()

			// #endif
			console.log('登录页');
			uni.hideLoading()
			const userInfor = uni.getStorageSync("wanlshop:user")
			if (userInfor && userInfor.token) {
				// #ifdef H5
				if (this.$jssdk.isWechat()) {
					uni.navigateTo({
						url: '/pages/user/auth-jssdk/auth-jssdk',
						success: res => {},
						fail: () => {},
						complete: () => {}
					});
					return;
				}
				// #endif

				// uni.reLaunch({
				// 	url: '/pages/tabbarcompotant/index/landlord'
				// });

			}
		},
		methods: {

			getCode() {
				console.log('重新获取code');
				uni.login({
					provider: 'weixin',
					success: res => {
						this.loginRes = res;
						console.log(res);
					},
					fail: err => {
						this.$wanlshop.msg(err.msg);
					}
				});
			},
			xiaokeaiShowtrue() {
				if (this.FormData.phone) {

					this.xiaokeaiShow = true
				} else {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					})
				}
			},
			checkResult(e) {
				if (e.detail == "success") {
					this.xiaokeaiShow = false
					this.sending()
				} else {
					uni.showToast({
						title: '请完成人机校验',
						icon: 'none'
					})
				}
			},
			goHome() {
				uni.reLaunch({
					url: '/pages/tabbarcompotant/index/landlord'
				});
			},
			// #ifdef APP
			//这个是自己的方法名
			openAuth() {
				this.$refs['authpup'].open() //调起自定义权限目的弹框,具体可看示例里面很详细
			},
			//用户授权权限后的回调
			changeAuth() {
				//这里是权限通过后执行自己的代码逻辑
				console.log('权限已授权，可执行自己的代码逻辑了');
				this.loginStorage()
			},
			// #endif
			CheckboxChange(e) {
				this.checked = e.detail.value[0];
			},
			loginWX() {
				let _this = this
				uni.showModal({
					title: '提示',
					content: '是否已仔细阅读《好饰商家版用户服务协议》《好饰商家版个人信息保护及隐私政策》？',
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
							_this.checked = true
							_this.getphone(_this.getPhoneNumberData, _this.getPhoneNumbertype)
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			// 号码登录，暂时支持微信小程序，后续版本逐渐开发
			decryptPhoneNumber(e, type) {
				this.getPhoneNumberData = e
				this.getPhoneNumbertype = type
				uni.setStorageSync('detail', e.detail)
				if (e.detail.errMsg != "getPhoneNumber:fail user deny") {
					if (!this.checked) {
						this.loginWX(() => {
							// 用户确认后，重新调用自身以触发登录
							this.decryptPhoneNumber(e, type)
						})
						return
					}
					this.getphone(this.getPhoneNumberData, this.getPhoneNumbertype)
				}
			},
			getphone(e, type) {
				this.$api.post({
					url: '/wanlshop/user/phone',
					data: {
						encryptedData: e.detail.encryptedData,
						iv: e.detail.iv,
						code: this.loginRes.code,
						invitation_code: uni.getStorageSync('invitation_code') || null,
						client_id: uni.getStorageSync("wanlshop:chat_client_id") || null,
						source: uni.getStorageSync('entrance') || null,
					},
					success: res => {
						console.log('登录成功', res);
						uni.setStorageSync("wanlshop:user", res.userinfo);
						this.$store.dispatch('user/login', res);
						this.$store.dispatch('cart/login');
						// 返回页面
						if (type == 'gongjiang' && (res.userinfo.level == 0 || res.userinfo.level == 5)) {
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/craftsman/guide'
								});
							}, 50)
							uni.hideLoading();
						} else {
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/tabbarcompotant/index/landlord'
								});
							}, 50)
							uni.hideLoading();
						}

					},
					fail: error => {
						this.getCode()
					}
				});
			},
			register() {
				this.$wanlshop.to('/pages/login/register')
			},
			password() {
				this.$wanlshop.to('password')
			},
			sending() { //验证码获取
				let that = this
				if (this.FormData.phone.length >= 11) {
					console.log(this.sendText)
					if (this.sendText != '发送验证码') {
						uni.showToast({
							title: '请勿重新获取',
							duration: 500,
							icon: "none"
						});
					} else {
						this.$api.get({
							url: '/sms/send',
							data: {
								event: 'mobilelogin',
								mobile: this.FormData.phone
							},
							success: res => {
								uni.showToast({
									title: '发送成功',
									duration: 500,
									icon: "none"
								});
								let timer_num = 60;
								let timeClock = setInterval(function() {
									timer_num--;
									that.sendText = timer_num + '秒后重新发送'
									that.Code = timer_num
									if (timer_num == 0) {
										clearInterval(timeClock);
										that.sendText = '重新发送'
									}
								}, 1000)
							},

						});
					}
				} else {
					uni.showToast({
						title: '请输入正确的手机号',
						duration: 500,
						icon: "none"
					});
				}
			},

			login() {
				if (!this.FormData.phone) {
					uni.showToast({
						title: '请输入手机号',
						duration: 500,
						icon: "none"
					});
					return
				}
				if (!this.checked) {
					// 显示协议确认框，并在用户同意后继续执行登录
					this.loginWX(() => this.login())
					return
				}

				let request = !this.swItch ? '/wanlshop/user/login' : '/wanlshop/user/mobilelogin' //请求链接地址
				if (this.swItch == true) {
					this.FormData.send = this.FormData.sendCode
				} else {
					this.FormData.send = this.FormData.sendPass
				}
				let data = [{ //post请求实体数数
						captcha: this.FormData.send,
						mobile: this.FormData.phone
					},
					{
						password: this.FormData.send,
						account: this.FormData.phone
					}
				]
				let req = this.swItch ? data[0] : data[1]
				req['reference'] = uni.getStorageSync('invitation_code') || null
				req['source'] = uni.getStorageSync("entrance") || null
				this.$api.post({ //登录请求
					url: request,
					data: req,
					success: res => {
						// #ifdef APP
						this.openAuth(res)
						this.logoData = res
						// #endif
						console.log(res, '------登录成功')
						// #ifndef APP
						uni.setStorageSync("wanlshop:user", res.userinfo);
						this.$store.dispatch('user/login', res);
						this.$store.dispatch('cart/login');
						setTimeout(res => {
							uni.hideLoading()
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/tabbarcompotant/index/landlord'
								});
							}, 50)
						})
						// #endif

						// #ifdef H5
						if (this.$jssdk.isWechat()) {
							uni.navigateTo({
								url: '/pages/user/auth-jssdk/auth-jssdk',
								success: res => {},
								fail: () => {},
								complete: () => {}
							});
							return;
						}
						// #endif


					},
					fail: res => {
						this.$wanlshop.msg(res.data.msg)
					}
				});
			},
			loginStorage() {
				console.log('loginStorage', this.logoData);
				uni.setStorageSync("wanlshop:user", this.logoData.userinfo);
				this.$store.dispatch('user/login', this.logoData);
				this.$store.dispatch('cart/login');
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/tabbarcompotant/index/landlord'
					});
				}, 50)

			},
			change(e) { //input 框输入事件
				if (this.swItch == true) {
					this.FormData.send = this.FormData.sendCode
				} else {
					this.FormData.send = this.FormData.sendPass
				}
				if (this.FormData.phone && this.FormData.send) {
					this.disabled = false
				} else {
					this.disabled = true
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.btngongjiang {
		background: none;
		border: none;
		font-size: 24rpx;


	}

	.btngongjiang::after {
		border: none;
	}

	::v-deep .u-checkbox-group {
		width: 34rpx;
		margin-right: 16rpx;
	}

	.wechatBtn {
		font-weight: 500;
		font-size: 31rpx;
		color: #EF5749 !important;
		border-radius: 8rpx 8rpx 8rpx 8rpx;
		border: 2rpx solid #EF5749;
		background: none !important;
	}

	/* @import url("auth.css"); */
	.pages {
		background-color: #FFF;
		height: 100vh;
		width: 100vw;
		padding: 0 16px;

		.btn {}

		.bg-grey {
			width: 64px;
			background-color: #FF4530;
			font-size: 12px;
			height: 2px;
		}

		.whactLog {
			display: flex;
			font-family: Source Han Sans;
			font-size: 12px;

			.imgSrc {
				color: #808080;
				width: 33%;
				margin-top: 68px;
				text-align: center;
			}
		}

		.whactLog image {
			width: 43px;
			height: 43px;
			margin-bottom: 8px;
		}

		.bg-green {
			background-color: #FFF;
			color: #FF4530;
		}

		.btn {
			width: 100%;
			display: flex;
			justify-content: center;
		}

		.log {
			height: 15vh;
			width: calc(100vw - 32rpx);
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.log image {
			width: 64px;
			height: 64px;
			border-radius: 19.22px;
		}

		.bottom-xian {
			margin-top: 94px;
			width: 100%;
			text-align: center;
		}

		.bottom-xian image {
			width: 100%;
			height: 19px;
		}

		.password {
			display: flex;
			justify-content: center;
			align-items: center;
			font-family: Source Han Sans;
			font-size: 14px;
			margin-top: 20px;
			color: #333333;

			.color {
				margin: 0 13px;
			}

			.xia {
				color: #D8D8D8
			}
		}

		.loginBtn {
			width: 355px;
			height: 43px;
			border-radius: 4px;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			padding: 10px;
			gap: 10px;
			font-family: Source Han Sans;
			font-size: 16px;
			color: #FFF;
			font-weight: 500;
			background: linear-gradient(108deg, #FF5E4C 16%, #FD3E28 51%, #FD2B13 80%);
			box-shadow: 0px 4px 10px 0px rgba(254, 43, 19, 0.3);
			margin: 10px auto;
		}

		.login {
			width: calc(100vw - 32rpx);
			height: 504rpx;
			opacity: 1;
			font-family: Source Han Sans;
			font-size: 16px;
			font-weight: 500;

			.bottom-title {
				display: flex;
				font-size: 12px;
				color: #808080;
				margin-top: 37px;
				margin-bottom: 10px;

				.shake-horizontal {
					animation-name: shake-horizontal;
					animation-duration: 100ms;
					animation-iteration-count: infinite;
					animation-timing-function: ease-in-out;
					animation-delay: 0s;
					animation-play-state: running;
				}

				.auth-clause checkbox {
					margin-right: 6rpx;
					transform: scale(0.7);
				}



				.auth-clause text {
					margin: 0 10rpx;
					color: #ED6D0F;
				}


			}

			.imgDui image {
				width: 14px;
				height: 14px;
				border-radius: 2px;
				margin-right: 15rpx;
			}

			.input-box {
				width: calc(100vw - 32rpx);
				height: 102px;

				.border-botttom {
					margin-top: 20rpx;
					border-top: none;
					border-bottom: 0.5px solid #eee;
				}
			}

			.left-title {
				font-family: Source Han Sans;
				font-weight: 500;
				font-size: 13px;
			}

			.center-title {
				display: flex;
				justify-content: space-between;

				.action {
					padding: 24rpx 60rpx 0;
				}
			}

			.right-title {
				position: relative;
				bottom: 5px;
			}
		}

		.cu-form-group .title {
			min-width: calc(4em + 15px);
		}

		.checkbox-input {
			width: 15px;
			height: 15px;
		}
	}
</style>